﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using MyLibrary.API.Core;

namespace MyLibrary.API.Net
{
    public static class RequestManager
    {
        public static HttpWebResponse Request(string url, WebMethod method, List<Param<string>> parameters)
        {
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
            Request.Method = method.Equals(WebMethod.GET) ? "GET" : "POST";
            Request.Timeout = 300000;
            string paramlist = BuildParameters(parameters);

            switch (method)
            {
                case WebMethod.POST://set the content type
                    Request.ContentType = "application/x-www-form-urlencoded";
                    byte[] bytedata = System.Text.Encoding.ASCII.GetBytes(paramlist); //set content length
                    Request.CookieContainer = new CookieContainer();  //setup cookies
                    #region put the byte data in the request
                    Request.ContentLength = bytedata.Length;
                    Stream requestStream = Request.GetRequestStream();
                    requestStream.Write(bytedata, 0, bytedata.Length);
                    requestStream.Close();
                    #endregion
                    break;
            }

            return (HttpWebResponse) Request.GetResponse();
        }

        public static string Request_String(string url, WebMethod method, List<Param<string>> parameters)
        {
            var response = Request(url, method, parameters);
            StreamReader reader = new StreamReader(response.GetResponseStream());
            return reader.ReadToEnd();

        }

        private static string BuildParameters(List<Param<string>> parameters)
        {
            List<string> paramlist = new List<string>();
            foreach (var param in parameters)
            {
                paramlist.Add(string.Format("{0}={1}", param.Name, param.Value));
            }

            return string.Join("&", paramlist.ToArray()) == string.Empty ? null : string.Join("&", paramlist.ToArray());
        }
    }
}
